<?php

namespace App\Service;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class LogisticService
{
    protected $client;

    protected $appCode = '60b8e12b5c3f4244a202dcec44b26809';

    public function __construct()
    {
        $this->client =  new Client(['verify' => false]);
    }

    /**
     * 获取物流信息
     *
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getLogisticCompany()
    {
        if (Cache::store('redis')->has('logistic_company')) {
            return Cache::store('redis')->get('logistic_company') ?? [];
        }
        return [
            'resultcode' => 200,
            'reason' => '查询支持的快递公司成功',
            'result' => [
                [
                    'com' => '顺丰',
                    'no' => 'sf'
                ],
                [
                    'com' => '申通',
                    'no' => 'st'
                ],
                [
                    'com' => '圆通',
                    'no' => 'yt'
                ],
                [
                    'com' => '韵达',
                    'no' => 'yd'
                ],
                [
                    'com' => '天天',
                    'no' => 'tt'
                ],
                [
                    'com' => '中通',
                    'no' => 'zt'
                ],
                [
                    'com' => '全峰',
                    'no' => 'qf'
                ],
                [
                    'com' => '京东快递',
                    'no' => 'jd'
                ],
                [
                    'com' => '百世快运',
                    'no' => 'bsky'
                ],
                [
                    'com' => '苏宁快递',
                    'no' => 'suning'
                ],
                [
                    'com' => '邮政',
                    'no' => 'yz'
                ]
            ]
        ];
    }

    /**
     * 获取物流信息
     *
     * @param $code 物流编码
     * @param $company_code 物流公司编码
     * @return array|mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getLogistic($code, $oder_id)
    {
        $res = $this->client->post('https://kuaidid.market.alicloudapi.com/danhao', [
            'headers' => [
                'Authorization' => "APPCODE {$this->appCode}",
                'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
            ],
            'form_params' => [
                'src' => $code
            ]
        ]);
        if ($res->getStatusCode() == 200) {
            $data = json_decode($res->getBody()->getContents(), true);
            if(isset($data['msg']['context'])) {
                $data['msg']['no'] = $code;
                return $data['msg'];
            }
        }
        return [];
    }
}
